<?php

namespace App\Http\Controllers;

use App\Jobs\SendEmail;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class Controller extends BaseController {
	use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

	public function __construct() {
		date_default_timezone_set('Asia/Shanghai');
	}
	protected $statusCodes = [
		'get_ok' => ['code' => 200, 'msg' => '获取数据成功'],
		'get_error' => ['code' => 404, 'msg' => '未发现该对象'],
		'add_ok' => ['code' => 200, 'msg' => '新增数据成功'],
		'add_error' => ['code' => 500, 'msg' => '新增数据失败'],
		'update_ok' => ['code' => 200, 'msg' => '更新数据成功'],
		'update_error' => ['code' => 500, 'msg' => '更新数据失败'],
		'delete_ok' => ['code' => 200, 'msg' => '删除数据成功'],
		'delete_error' => ['code' => 500, 'msg' => '删除数据失败'],
		'empty_error' => ['code' => 500, 'msg' => '参数为空或无效'],
		'no_auth' => ['code' => 403, 'msg' => '你没有该操作权限,请联系管理员！'],
		'op_ok' => ['code' => 200, 'msg' => '操作成功'],
		'op_error' => ['code' => 500, 'msg' => '操作失败'],
		'resume_owner_no_auth' => ['code' => 403, 'msg' => '您没有权限,请联系简历拥有者！'],
	];
	public function page(Request $request) {
		$page = $request->input('page') ? $request->input('page') : 1;
		$pageNum = $request->input('perPage') ? $request->input('perPage') : 10;
		$skip = ($page - 1) * $pageNum;
		$take = $pageNum;
		return ['skip' => $skip, 'take' => $take];
	}

	public function respond($status, $data = []) {
		$status = $this->statusCodes[$status];
		if (!empty($data)) {
			$status['data'] = $data;
		}
		return response()->json($status);
	}
	//将图片url转化为base64
	public function fileToBase64($file) {
		$base64_file = '';
		if (file_exists($file)) {
			$mime_type = mime_content_type($file);
			$base64_data = base64_encode(file_get_contents($file));
			$base64_file = 'data:' . $mime_type . ';base64,' . $base64_data;
		}
		return $base64_file;
	}

	//初始化基础数据(组织结构、员工、角色权限)
	protected function initBaseData() {
		$user = \Auth::guard('api')->user();
		$user = \App\Models\User::find($user->id);
		if (!$this->getDevice()) {
			//app
			$user->company_id = $user->appcompany_id;
		}
		$time = time();
		//初始化部门
		$company_id = $user->company_id;
		$company = \App\Models\Company::find($company_id);
		if (!empty($company_id)) {
			$root = \App\Models\Department::where('parent_id', '=', null)->first();
			$child = \App\Models\Department::where(
				['company_id' => $company_id, 'depth' => 1])->first();
			if (empty($child)) {
				$child = \App\Models\Department::create(['name' => $company->name, 'company_id' => $company_id, 'created_at' => time(), 'updated_at' => time()]);
				$child->makeChildOf($root);
			}
			//初始化员工
			\App\Models\Staff::firstOrCreate(
				['name' => $user->name, 'mobile' => $user->mobile, 'user_id' => $user->id, 'company_id' => $user->company_id, 'dept_id' => $child->id, 'role_status' => 1]);
		}
		//初始化简历/职位
		$check_position = \App\Models\Position::where(['user_id' => $user->id, 'company_id' => $company_id, 'name' => '示例', 'dept_name' => '示例'])->first();
		if (!empty($check_position)) {
			$inti_position_id = $check_position->id;
		} else {
			$inti_position = \App\Models\Position::firstOrCreate(['user_id' => $user->id, 'company_id' => $company_id, 'name' => '示例', 'dept_name' => '示例'], Config::get('info.position_init_data')
			);
			if (!empty($inti_position)) {
				$inti_position_id = $inti_position->id;
			}

		}
		$check_resume = \App\Models\Resume::where(['position_id' => $inti_position_id])->first();
		if (empty($check_resume)) {
			$get_resume_id = \App\Models\Resume::firstOrCreate(['position_id' => $inti_position_id], ['user_id' => $user->id, 'owner_id' => $user->id, 'company_id' => $company_id, 'name' => '示例', 'sex' => '男', 'mobile' => '10123456789', 'area' => '北京,北京,朝阳区', 'job_date' => '1420070400', 'birthday' => '631152000', 'position' => 'CEO', 'edu' => '博士及以上', 'company_name' => 'XX有限公司', 'is_job' => 1]);
			$init_resume_id = $get_resume_id->id;
			\Log::info('resume_id:' . $init_resume_id);
			//工作经历
			\App\Models\Job::firstOrCreate(['resume_id' => $init_resume_id], ['type' => '职能/高级管理,高级管理职位,CEO/总裁/总经理', 'name' => 'CEO/总裁/总经理', 'company_name' => 'XX有限公司', 'company_industry' => 'XX有限公司', 'content' => Config::get('info.job_content_data'), 'start_date' => '1420041600', 'end_date' => '1530403200']);
			//项目经历
			\App\Models\Item::firstOrCreate(['resume_id' => $init_resume_id], ['name' => 'XX项目', 'role' => 'CEO', 'discription' => '1、项目运作，管理，运营
2、项目的其他所有事物', 'harvest' => '1、成功引入百万个用户
2、月销售额达千万级', 'start_date' => '1420041600', 'end_date' => '1530403200']);
			//教育经历
			\App\Models\Education::insert([
				['resume_id' => $init_resume_id, 'name' => 'XX大学', 'major' => '物理', 'edu' => '硕士', 'start_date' => '1199116800', 'end_date' => '1325347200', 'experience' => '获得学校计算机比赛一等奖', 'created_at' => $time, 'updated_at' => $time],
				['resume_id' => $init_resume_id, 'name' => 'XX大学', 'major' => '物理', 'edu' => '博士及以上', 'start_date' => '1325347200', 'end_date' => '1420041600', 'experience' => '获得全额奖学金', 'created_at' => $time, 'updated_at' => $time],
			]);
		}
		//初始化公司地点
		\App\Models\Address::firstOrCreate(
			['address' => '其他', 'user_id' => $user->id, 'company_id' => $company_id, 'created_at' => $time, 'updated_at' => $time]);
		//初始化角色、权限
		$role_flag = $company->role_flag;
		$get_role = Role::where('guard_name', $role_flag)->first();
		if (empty($get_role) && !empty($role_flag)) {
			$role = Role::insert([
				['name' => '管理员', 'type' => 1, 'is_delete' => 2, 'remarks' => '拥有所有权限', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => '招聘专员', 'type' => 2, 'is_delete' => 2, 'remarks' => '具备招聘的所有权限，不具备面试权限，比如填写面试意见', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => '面试官', 'type' => 2, 'is_delete' => 2, 'remarks' => '具备HR指定的人员面试权限', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
			]
			);
		}
		$get_permission = Permission::where('guard_name', $role_flag)->first();
		if (empty($get_permission) && !empty($role_flag)) {
			Permission::insert([
				//简历
				['name' => 'resume_add', 'alias' => '新增简历', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'resume_edit', 'alias' => '编辑简历', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'resume_remove', 'alias' => '删除简历', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				//职位
				['name' => 'position_add', 'alias' => '新增职位', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'position_edit', 'alias' => '编辑职位', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'position_remove', 'alias' => '删除职位', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				//权限管理
				['name' => 'role_add', 'alias' => '新增角色', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'role_edit', 'alias' => '修改角色', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'role_remove', 'alias' => '删除角色', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'role_user', 'alias' => '分配用户', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'role_permission', 'alias' => '分配权限', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				//设置
				['name' => 'flow_add', 'alias' => '增加流程', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'flow_edit', 'alias' => '修改流程', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'flow_remove', 'alias' => '删除流程', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'flow_use', 'alias' => '开启、关闭流程', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],

				['name' => 'evaluate_add', 'alias' => '增加评价表', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'evaluate_edit', 'alias' => '修改评价表', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'evaluate_remove', 'alias' => '删除评价表', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],

				['name' => 'offer_set', 'alias' => 'offer模版配置', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'role_email_set', 'alias' => '邮件配置', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'address_set', 'alias' => '地点配置', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				//流程
				['name' => 'flow_start', 'alias' => '启动流程', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'check_first', 'alias' => '初审', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'check_first_view', 'alias' => '初审查看', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'call', 'alias' => '邀约', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'call_view', 'alias' => '邀约查看', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'interview_edit', 'alias' => '编辑面试官和时间', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'send_offer', 'alias' => '发放offer', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'send_offer_view', 'alias' => 'offer结果查看', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'job', 'alias' => '入职', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'job_view', 'alias' => '入职查看', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
			]
			);
		}
		//系统默认权限的分配
		$hr_role = Role::where(['guard_name' => $role_flag, 'name' => '招聘专员'])->first();
		$get_hr = Permission::where('guard_name', $role_flag)->where('name', 'like', 'role_%')->pluck('id');
		$hr_permission = Permission::whereNotIn('id', $get_hr)->where('guard_name', $role_flag)->get();
		$user->guard_name = $role_flag;
		if (!$user->hasRole('管理员')) {
			$user->assignRole('管理员'); //分配管理员角色
			$hr_role->givePermissionTo($hr_permission); //分配HR角色权限
		}
		\Log::info('role_flag:' . $role_flag);
		//初始化主招聘流程
		$get_role_ids = Role::where(['name' => '管理员', 'type' => 1, 'is_delete' => 2, 'guard_name' => $role_flag])->first();
		\Log::info('role_ids:' . json_encode($get_role_ids));
		$get_role_id = 0;
		if (!empty($get_role_ids)) {
			$get_role_id = $get_role_ids->id;
		}
		\Log::info('get_role_id:' . $get_role_id);
		$get_flow = \App\Models\Flow::firstOrCreate(['company_id' => $company_id, 'name' => '主招聘流程']);
		$fid = $get_flow->id;
		$step1 = \App\Models\Step::firstOrCreate(['flow_id' => $fid, 'role_id' => $get_role_id, 'name' => '一面']);
		$step1_id = $step1->id;
		$check_step1 = \App\Models\Reason::where(['step_id' => $step1_id])->first();
		if (empty($check_step1)) {
			\App\Models\Reason::insert([
				['step_id' => $step1_id, 'name' => '薪资问题', 'created_at' => $time, 'updated_at' => $time],
				['step_id' => $step1_id, 'name' => '项目问题', 'created_at' => $time, 'updated_at' => $time],
				['step_id' => $step1_id, 'name' => '已有offer', 'created_at' => $time, 'updated_at' => $time],
			]);
			Permission::insert([
				//一面
				['name' => 'sys_step_op_' . $step1_id, 'alias' => '一面评价(主招聘流程)', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'sys_step_view_' . $step1_id, 'alias' => '一面评价查看(主招聘流程)', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
			]);
		}
		$step2 = \App\Models\Step::firstOrCreate(['flow_id' => $fid, 'role_id' => $get_role_id, 'name' => '二面']);
		$step2_id = $step2->id;
		$check_step2 = \App\Models\Reason::where(['step_id' => $step2_id])->first();
		if (empty($check_step2)) {
			\App\Models\Reason::insert([
				['step_id' => $step2_id, 'name' => '薪资问题', 'created_at' => $time, 'updated_at' => $time],
				['step_id' => $step2_id, 'name' => '项目问题', 'created_at' => $time, 'updated_at' => $time],
				['step_id' => $step2_id, 'name' => '已有offer', 'created_at' => $time, 'updated_at' => $time],
			]);
			Permission::insert([
				//二面
				['name' => 'sys_step_op_' . $step2_id, 'alias' => '二面评价(主招聘流程)', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'sys_step_view_' . $step2_id, 'alias' => '二面评价查看(主招聘流程)', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
			]);
		}
		$step3 = \App\Models\Step::firstOrCreate(['flow_id' => $fid, 'role_id' => $get_role_id, 'name' => '三面']);
		$step3_id = $step3->id;
		$check_step3 = \App\Models\Reason::where(['step_id' => $step3_id])->first();
		if (empty($check_step3)) {
			\App\Models\Reason::insert([
				['step_id' => $step3_id, 'name' => '薪资问题', 'created_at' => $time, 'updated_at' => $time],
				['step_id' => $step3_id, 'name' => '项目问题', 'created_at' => $time, 'updated_at' => $time],
				['step_id' => $step3_id, 'name' => '已有offer', 'created_at' => $time, 'updated_at' => $time],
			]);
			Permission::insert([
				//三面
				['name' => 'sys_step_op_' . $step3_id, 'alias' => '三面评价(主招聘流程)', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
				['name' => 'sys_step_view_' . $step3_id, 'alias' => '三面评价查看(主招聘流程)', 'guard_name' => $role_flag, 'created_at' => $time, 'updated_at' => $time],
			]);
		}
		//自定义流程权限分配
		$flow_leader_role = Role::where(['guard_name' => $role_flag, 'name' => '面试官'])->first();
		$flow_leader_permission = Permission::where('guard_name', $role_flag)->where('name', 'like', 'sys_step_%')->get();
		$flow_hr_permission = Permission::where('guard_name', $role_flag)->where('name', 'like', 'sys_step_view_%')->get();
		$hr_role->givePermissionTo($flow_hr_permission); //分配HR自定义角色权限
		$flow_leader_role->givePermissionTo($flow_leader_permission); //分配面试官自定义角色权限
	}

//发送邮件
	public function sendMail($content, $to, $subject) {
		$userInfo = \Auth::guard('api')->user();
		$mailInfo = DB::table('email_sets')
			->where('company_id', $userInfo->company_id)
			->first();
		if (!empty($mailInfo) && ($mailInfo->type == 1 || $mailInfo->type == 0)) {
			$encryption = '';
		} else if (!empty($mailInfo) && $mailInfo->type == 2) {
			$encryption = 'ssl';
		} else if (!empty($mailInfo) && $mailInfo->type == 3) {
			$encryption = 'tls';
		}
		if (empty($mailInfo) || $mailInfo->is_use == 2) {
			return response()->json(['code' => 400, 'msg' => '邮件配置异常', 'data' => ""]);
		}
		if (empty($mailInfo) || empty($mailInfo->host) || empty($mailInfo->port) || empty($mailInfo->user_name)) {
			return response()->json(['code' => 400, 'msg' => '邮件配置异常', 'data' => ""]);
		}
		$host = $mailInfo->host ?? 'smtp.mailgun.org';
		$port = $mailInfo->port ?? '587';
		$username = $mailInfo->user_name ?? '';
		$password = $mailInfo->password ?? '';
		$address = $mailInfo->address ?? 'hello@example.com';
		$name = $mailInfo->name ?? '罗姆网络';
		Config::set('mail.encryption', $encryption);
		Config::set('mail.host', $host);
		Config::set('mail.port', $port);
		Config::set('mail.username', $username);
		Config::set('mail.password', $password);
		Config::set('mail.from', ['address' => $address, 'name' => $name]);
		try {
			Mail::send('emails.test',
				['content' => $content],
				function ($message) use ($address, $name, $to, $subject) {
					$message->from($address, $name)->to($to)->subject($subject);});
			if (count(Mail::failures()) > 0) {
				return response()->json(['code' => 400, 'msg' => '邮件发送失败', 'data' => ""]);
			} else {
				return response()->json(['code' => 200, 'msg' => '邮件发送成功', 'data' => ""]);
			}
		} catch (\Exception $exception) {
			$str = utf8_encode($exception->getMessage());
			if (strlen($str) > 251) {
				$str = substr($str, 0, 210);
			}
			return response()->json(['code' => 400, 'msg' => '邮件发送失败', 'data' => ['errorInfo' => $str . '"']]);
		}
	}
	//    发送offer
	public function sendOfferInfo($id) {
		\Log::info('调用方法开始 date' . date('Y-m-d H:i:s'));
		$user = \Auth::guard('api')->user();
		$userInfo = \App\Models\User::find($user->id);
		$type = 1;
		if (!$this->getDevice()) {
			$userInfo->company_id = $userInfo->appcompany_id;
		} else {
			$type = 2;
		}
		$mailInfo = DB::table('email_sets')
			->where('company_id', $userInfo->company_id)
			->first();
		if (empty($mailInfo) || (!empty($mailInfo) && empty($mailInfo->user_name))) {
			return response()->json(['code' => 400, 'msg' => '邮件服务器未配置', 'data' => ""]);
		}
		$cmpInfo = DB::table('companies')->where('id', $userInfo->company_id)->first();
//        $name = strpos($mailInfo->offer_content, '#候选人姓名#');
		//        $dept =  strpos($mailInfo->offer_content, '#入职部门#');
		//        $position = strpos($mailInfo->offer_content, '#入职岗位#');
		//        $salary = strpos($mailInfo->offer_content, '#薪资#');
		//        $address = strpos($mailInfo->offer_content, '#地址#');
		//        $time = strpos($mailInfo->offer_content, '#入职时间#');
		//        $cmpName = strpos($mailInfo->offer_content, '#公司名称#');
		//        if ($name === false || $dept === false || $position === false || $salary ===false || $address === false || $time === false || $cmpName === false) {
		//            return response()->json(['code' => 400, 'msg' => 'offer模板格式错误', 'data' => ""]);
		//        }
		$offerInfo = DB::table('offers')
			->where('id', $id)
			->first();
		$content = str_replace('#候选人姓名#', $offerInfo->name, $mailInfo->offer_content);
		$content = str_replace('#入职部门#', $offerInfo->dept, $content);
		$content = str_replace('#职位#', $offerInfo->position, $content);
		$content = str_replace('#薪资#', $offerInfo->salary, $content);
		$content = str_replace('#入职时间#', date('Y/m/d', $offerInfo->entry_time), $content);
		$content = str_replace('#联系人#', $offerInfo->person, $content);
		$content = str_replace('#联系电话#', $offerInfo->mobile, $content);
		$content = str_replace('#地址#', $offerInfo->address, $content);
		$content = str_replace('#公司名称#', $cmpInfo->name, $content);
		$message = $content;
		$to = $offerInfo->email;
		$title = $mailInfo->offer_title;
		$title = str_replace('#候选人姓名#', $offerInfo->name, $title);
		$title = str_replace('#入职部门#', $offerInfo->dept, $title);
		$title = str_replace('#职位#', $offerInfo->position, $title);
		$title = str_replace('#薪资#', $offerInfo->salary, $title);
		$title = str_replace('#入职时间#', date('Y/m/d', $offerInfo->entry_time), $title);
		$title = str_replace('#联系人#', $offerInfo->person, $title);
		$title = str_replace('#联系电话#', $offerInfo->mobile, $title);
		$title = str_replace('#地址#', $offerInfo->address, $title);
		$title = str_replace('#公司名称#', $cmpInfo->name, $title);
		$subject = $title;
		// $result = $this->sendMail($message,$to,$subject);
		//  return $result;
		\Log::info('任务队列开始111 date' . date('Y-m-d H:i:s'));
		\Log::info('xx' . json_encode($userInfo));
		$this->dispatch(new SendEmail($userInfo, $message, $to, $subject, $type));
		return response()->json(['code' => 200, 'msg' => '邮件发送成功', 'data' => ""]);
	}
	public function getDevice() {
		$agent = $_SERVER['HTTP_USER_AGENT'];
		if (true == preg_match("/.+Windows.+/", $agent)) {
			return true;
		} elseif (true == preg_match("/.+Macintosh.+/", $agent)) {
			return true;
		} else {
			return false;
		}
	}
}
